package com.neusoft.chatserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.neusoft.chatserver.dto.FileDTO;
import com.neusoft.chatserver.dto.RespBean;
import com.neusoft.chatserver.entity.Message;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;

@CrossOrigin
@RestController
@RequestMapping("/chat")
public class FileController {

    @Autowired
    private RedisTemplate redisTemplate;

    private String PROVIDER_URL = "http://localhost:10007/";
    private String FILEPATH = "E:\\chat\\";

    @PostConstruct
    public void init() {
        String server1 = (String) redisTemplate.opsForValue().get("SERVER1");
        String filepath = (String) redisTemplate.opsForValue().get("FILEPATH");
        PROVIDER_URL = "http://" + server1 + ":10007/";
        FILEPATH = filepath;
    }

    public void uploadToOSS(String path, String filename) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tNzTuF1JxNVNmh8zQXu";
        String accessKeySecret = "QbObrco29cRA6kQguU322A9Res2Gke";


// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 创建PutObjectRequest对象。
// 依次填写Bucket名称（例如examplebucket）、Object完整路径（例如exampledir/exampleobject.txt）和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
// 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        PutObjectRequest putObjectRequest = new PutObjectRequest("npmsneu", "npmsneu/" + filename, new File(path));

// 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);

// 上传文件。
        ossClient.putObject(putObjectRequest);

// 关闭OSSClient。
        ossClient.shutdown();
    }

    @PostMapping(value = "/uploadFile")
    public RespBean uploadFile(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        RespBean respBean = RespBean.ok(200, "File uploaded successfully!");
        LocalDate today = LocalDate.now();
        Instant timestamp = Instant.now();
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String filenames = today + String.valueOf(timestamp.toEpochMilli()) + "." + ext;
        file.transferTo(new File(FILEPATH + filenames));
//        resUrl.put("src", "/pic/" + filenames);
        uploadToOSS(FILEPATH + filenames, filenames);
        String url = "https://npmsneu.oss-cn-beijing.aliyuncs.com/npmsneu/" + filenames;

        FileDTO fileDTO = new FileDTO(url, file.getOriginalFilename());
        respBean.setObj(fileDTO);
        return respBean;
    }

    @PostMapping("/uploadAudio")
    @ResponseBody
    public RespBean upaudio(@RequestParam(value = "file") MultipartFile file) throws IOException {
        RespBean respBean = RespBean.ok(200, "Audio uploaded successfully!");
        LocalDate today = LocalDate.now();
        Instant timestamp = Instant.now();
        String filenames = today + String.valueOf(timestamp.toEpochMilli()) + ".mp3";
        String pathname = FILEPATH + filenames;
        file.transferTo(new File(pathname));

        uploadToOSS(pathname, filenames);
        String url = "https://npmsneu.oss-cn-beijing.aliyuncs.com/npmsneu/" + filenames;
        FileDTO fileDTO = new FileDTO(url, file.getOriginalFilename());
        respBean.setObj(fileDTO);
        return respBean;
    }
}
